/* eslint-disable */

// import { createApp } from 'vue'
import "ant-design-vue/dist/reset.css";
// import { createLoginUsername, createLoginPhone } from './components/login/login.js'
import { createVerificationCode } from "./components/verificationCode/verificationCode.js";
// , createTopAvatar, createTopInfo
import { createPerson } from "./components/person/person.js";
import { createUserElement } from "./components/person/index.js";
import { createAssetFund } from "./components/fund/index.js";
// import { createInStock } from './components/transaction/index.js'
import { observeLoginElements } from "./watch/login/login.js";

import { createTradingAction } from "./components/trading/index.js";
// import './http/InterceptRequests.js'

// 监听登录相关元素

// function getInitialValues() {
//     const order = document.querySelectorAll('.order_types_container')[0];
//     if (!order) return {};

//     const buyOrSell = order.querySelector('.mantine-wz61vw')?.value;
//     const timeSlot = document.querySelector('.mantine-1t5amwr > .tr-border-c-brand-3');
//     const startTime = document.querySelector('.mantine-1626jtb')?.value;
//     const endTime = document.querySelector('.mantine-17whd58')?.value;
//     const transType = document.querySelector('.mantine-15he3b8 > .gZDgCa');

//     return {
//         buyOrSell,
//         timeSlot,
//         startTime,
//         endTime,
//         transType
//     };
// }

import { getElement } from '@/content-scripts/getElement.js'


function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
  return null;
}

// 语言监听管理器 - 单例模式
const LanguageWatcher = {
  intervalId: null,
  refreshTimeout: null,
  lastLanguage: null,
  isInitialized: false,
  isRefreshing: false, // 防止重复刷新

  init() {
    if (this.isInitialized) {
      console.log('LanguageWatcher 已经初始化，跳过重复初始化');
      return;
    }

    this.lastLanguage = localStorage.getItem('language');
    console.log('LanguageWatcher 初始化，当前语言:', this.lastLanguage);

    // 启动监听
    this.startWatching();
    this.isInitialized = true;
  },

  startWatching() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }

    this.intervalId = setInterval(() => {
      const currentLanguage = localStorage.getItem('language');

      // 详细调试信息
      if (currentLanguage !== this.lastLanguage) {
        console.log('=== 语言变化检测 ===');
        console.log('上次语言:', this.lastLanguage);
        console.log('当前语言:', currentLanguage);
        console.log('时间戳:', new Date().toLocaleTimeString());
        console.log('是否正在刷新:', this.isRefreshing);

        if (currentLanguage !== null && this.lastLanguage !== null && !this.isRefreshing) {
          console.log('检测到有效语言变化，准备刷新页面');
          this.lastLanguage = currentLanguage;
          this.isRefreshing = true;

          // 防抖刷新
          if (this.refreshTimeout) {
            clearTimeout(this.refreshTimeout);
          }
          this.refreshTimeout = setTimeout(() => {
            console.log('执行页面刷新');
            location.reload();
          }, 1000);
        } else {
          // 更新 lastLanguage，但不刷新
          this.lastLanguage = currentLanguage;
          console.log('语言值无效或正在刷新，跳过刷新');
        }
      }
    }, 500);
  },

  stopWatching() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
    if (this.refreshTimeout) {
      clearTimeout(this.refreshTimeout);
      this.refreshTimeout = null;
    }
  },

  // 重置刷新状态
  resetRefreshState() {
    this.isRefreshing = false;
  }
};

// 初始化语言监听器
LanguageWatcher.init();

window.addEventListener('storage', function (event) {
  console.log('storage 事件监听到:', event.key, event.newValue);
  if (event.key === 'language') {
    location.reload();
  }
});

// 初始化函数
function initialize() {
  console.log('=== initialize 函数开始执行 ===');
  console.log('当前URL:', location.href);

  // 重置语言监听器的刷新状态
  LanguageWatcher.resetRefreshState();

  observeLoginElements();

  // 优先从 cookie 获取语言设置
  if (getCookie('lang')) {
    console.log('从 cookie 获取到语言:', getCookie('lang'));
    setLanguage(getCookie('lang'));
  }

  // 监听页面语言元素变化 - 只在首次加载时执行
  if (!getElement("login.language")[0]) {
    let langInterval = setInterval(() => {
      const langElement = getElement("login.language")[0];
      if (langElement) {
        const langText = langElement.innerHTML;
        console.log('检测到页面语言元素:', langText);
        if (langText === '简体中文') {
          setLanguage('cn');
        } else if (langText === 'English' || langText === 'English (US)') {
          setLanguage('en');
        }
        clearInterval(langInterval);
      }
    }, 100);
  }

  initFirst();
  console.log('当前 localStorage language:', localStorage.getItem('language'));
  console.log('=== initialize 函数执行完成 ===');
}
// import { detectingNodes } from '@/content-scripts/detectingNodes.js'
import { observeHoldAsset } from '@/content-scripts/components/person/holdAsset.js'

// import { getElement } from '@/content-scripts/getElement.js'
console.log(getElement("header.avatar"), "getElement('header.avatar')");

function initFirst() {
  const username = localStorage.getItem('username')
  console.log(username, 'usernameusernameusernameusername');
  localStorage.setItem('pagePagination', JSON.stringify({
    "current": 1,
    "pageSize": 10,
    isChange: true
  }))
  console.log(localStorage.getItem('userInfo'), "localStorage.getItem('userInfo')");
  if (JSON.parse(localStorage.getItem('userInfo')) && username == JSON.parse(localStorage.getItem('userInfo')).email) {
    createVerificationCode();
    setTimeout(() => {
      // detectingNodes()
    }, 5500)

    // let elementIntervals = setInterval(() => {
    //   if (document.querySelectorAll('.fbxVZq').length > 0||document.querySelectorAll('.my-avatar').length > 0) {
    //     // createTopAvatar()
    //     // createTopInfo();
    //     console.log('createUserElement11111111111111111111111');
        
        createUserElement()

    //     clearInterval(elementIntervals);
    //   }
    // }, 100);

    const currentUrl = window.location.href
    console.log(currentUrl, 'currentUrl is not defined1');
    if (currentUrl) {
      // if (currentUrl == 'https://www.gate.com/zh' || currentUrl == 'https://www.gate.com' || currentUrl == 'https://www.gate.com/zh/myaccount/profile/setup_totp' || currentUrl == 'https://www.gate.com/myaccount/profile/setup_totp') {

      // }

      // 统一等待元素加载完成
      if ((currentUrl.includes('https://www.gate.com/zh/myaccount/profile') || currentUrl.includes('https://www.gate.com/myaccount/profile')) && !currentUrl.includes('setup_totp') && !currentUrl.includes('settings') && !currentUrl.includes('security-setting') && !currentUrl.includes('kyc_home') && !currentUrl.includes('sub-account-manage') && !currentUrl.includes('api-key') && !currentUrl.includes('coupon_center') && !currentUrl.includes('point_manage') && !currentUrl.includes('tickets_list')) {
        let elementInterval = setInterval(() => {
          if (getElement("header.avatar").length > 0) {
            createUserElement();
            createPerson();
            observeHoldAsset()
            createAssetFund();
            createTradingAction()
            clearInterval(elementInterval);
          }
        }, 100);
      }
      if ((currentUrl.includes('https://www.gate.com/zh/trade') || currentUrl.includes('https://www.gate.com/trade') || currentUrl.includes('https://www.gate.com/zh/futures') || currentUrl.includes('https://www.gate.com/futures')) && !currentUrl.includes('https://www.gate.com/zh/futures-') && !currentUrl.includes('https://www.gate.com/futures-')) {
        let interval = setInterval(() => {
          if (getElement("header.avatar").length > 0) {
            createUserElement();
            createPerson();
            createAssetFund();
            console.log('加载createTradingAction');
            
            createTradingAction()
            clearInterval(interval);
          }
        }, 100);
      }
    }



    // createInStock()
    // createAssetFund();
    // createTradingAction()
  } else {
    chrome.runtime.sendMessage({
      type: "proxy",
      method: "GET",
      url: `/user/info`,
      body: { email: localStorage.getItem('username') }
    }, (response) => {

      localStorage.setItem('userInfo', JSON.stringify(response.data));
      createVerificationCode();
      setTimeout(() => {
        // detectingNodes()
      }, 5500)
      const currentUrl = window.location.href
      // 统一等待元素加载完成
      let elementInterval = setInterval(() => {
        if (getElement("header.avatar").length > 0) {
          createUserElement();
          createPerson();
          createAssetFund();
          createTradingAction()
          clearInterval(elementInterval);
        }

        console.log(currentUrl, 'currentUrl is not defined2');

        if (currentUrl) {
          if (currentUrl == 'https://www.gate.com/zh' || currentUrl == 'https://www.gate.com' || currentUrl == 'https://www.gate.com/zh/myaccount/profile/setup_totp' || currentUrl == 'https://www.gate.com/myaccount/profile/setup_totp') {
            let elementIntervals = setInterval(() => {
              if (getElement("header.avatar").length > 0) {
                // createTopAvatar()
                // createTopInfo();
                createUserElement()

                clearInterval(elementIntervals);
              }
            }, 100);
          }
          if ((currentUrl.includes('https://www.gate.com/zh/myaccount/profile') || currentUrl.includes('https://www.gate.com/myaccount/profile')) && !currentUrl.includes('setup_totp') && !currentUrl.includes('settings') && !currentUrl.includes('security-setting') && !currentUrl.includes('kyc_home') && !currentUrl.includes('sub-account-manage') && !currentUrl.includes('api-key') && !currentUrl.includes('coupon_center') && !currentUrl.includes('point_manage') && !currentUrl.includes('tickets_list')) {

            observeHoldAsset()

          }
        }

      }, 100);

      createAssetFund();
      // createInStock()

      // createTradingAction()
      // detectingNodes()
      // 监听函数
      // const token = response.data.token;
      // 保存token
      // chrome.storage.local.set({ token: token }, () => {
      //   console.log("Token 已存储");
      // });
      console.log(`[代理响应] 状态: ${response.code}, 数据: ${JSON.stringify(response.data)}`);
    });
  }
}

// 页面加载时初始化
window.onload = initialize();

// 监听URL变化 - 添加防抖
let lastUrl = location.href;
let urlChangeTimeout = null;

new MutationObserver(() => {
  const currentUrl = window.location.href;
  console.log(currentUrl, 'currentUrl is not defined3');
  if (currentUrl) {
    if (currentUrl !== lastUrl) {
      console.log('URL变化检测:', lastUrl, '->', currentUrl);
      lastUrl = currentUrl;

      // 防抖：避免频繁调用initialize
      if (urlChangeTimeout) {
        clearTimeout(urlChangeTimeout);
      }
      urlChangeTimeout = setTimeout(() => {
        console.log('执行URL变化后的初始化');
        initialize();
      }, 500); // 500ms后执行
    }
  }

}).observe(document, { subtree: true, childList: true });

chrome.runtime.onMessage.addListener(function (request) {
  if (request.target === "CONTENT" && request.from === "BACKGROUND") {
    // 处理消息
  }
});

// 统一的语言设置函数
function setLanguage(lang) {
  const currentLang = localStorage.getItem('language');
  console.log('setLanguage 调用:', lang, '当前语言:', currentLang);

  // 更严格的检查
  if (lang && lang !== currentLang && (lang === 'cn' || lang === 'en')) {
    console.log('设置语言:', lang, '当前语言:', currentLang);
    localStorage.setItem('language', lang);
    console.log('语言设置完成:', localStorage.getItem('language'));
  } else {
    console.log('跳过语言设置 - 值相同、无效或格式不正确:', lang);
  }
}
